﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Net.NetworkInformation;
using System.Management;

namespace MSysMonNET
{
    public class MSysCheckNetwork
    {
        /// <summary>
        /// This method sends a ping request to a given host 
        /// to check its network availability
        /// </summary>
        /// <param name="hostName">The target host to send the ping request</param>
        /// <returns>the roundtrip duration, or a negative value in case it fails.</returns>
        public long checkPing(String hostName)
        {
            Ping pingSender = new Ping ();
            PingOptions options = new PingOptions ();

            // Use the default Ttl value which is 128,
            // but change the fragmentation behavior.
            options.DontFragment = true;

            // Create a buffer of 32 bytes of data to be transmitted.
            string data = "aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa";
            byte[] buffer = Encoding.ASCII.GetBytes (data);
            int timeout = 120;
            PingReply reply = pingSender.Send (hostName, timeout, buffer, options);

            if (reply.Status == IPStatus.Success) return reply.RoundtripTime;

            return -1;

        }
        /// <summary>
        /// Get a server scope which I can use to connect to a remote server. Given
        /// this instance, I will not have to connect each time I inquire the server's
        /// status on something through WMI.
        /// </summary>
        /// <param name="hostName">the remote server network address</param>
        /// <param name="userName">the user account with privileges to conect</param>
        /// <param name="passWord">the user's password</param>
        /// <returns></returns>
        public static ManagementScope getServerScope(string hostName, string userName, string passWord)
        {
            ManagementScope clsReturn;

            ConnectionOptions options = new ConnectionOptions();
            options.Username = userName;
            options.Password = passWord;

            try
            {
                clsReturn =
                new ManagementScope(
                    "\\\\" + hostName + "\\root\\cimv2", options);
                clsReturn.Connect();

                return clsReturn;
            }
            catch
            {
                return null;
            }       
        }
    }

}
